package java_util.coo_util.Log;

import java_util.coo_util.C_String;
import java_util.interfaceType.I_Log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class C_LogTxtSave implements I_Log {
    public String deviceInfo;
    long msgIndex;
    long fileIndex;
    String prefixPath, fileName, _saveFullPath;
    BufferedWriter bw = null;
    StringBuilder ssb = new StringBuilder();

    public String o_saveFullPath() {
        return _saveFullPath;
    }

    static List<C_LogTxtSave> o_localLogs = new ArrayList<C_LogTxtSave>();

    public C_LogTxtSave(String deviceInfo, String prefixPath) {
        if (prefixPath == null) {
//             prefixPath = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
//             prefixPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);    		 
            prefixPath = System.getProperty("user.dir");
        }
        o_localLogs.add(this);
        deviceInfo = deviceInfo.replace("\\", "");
        deviceInfo = deviceInfo.replace("/", "");
        deviceInfo = deviceInfo.replace(":", "");
        deviceInfo = deviceInfo.replace("?", "");
        deviceInfo = deviceInfo.replace("*", "");
        deviceInfo = deviceInfo.replace("\"", "");
        deviceInfo = deviceInfo.replace("<", "");
        deviceInfo = deviceInfo.replace(">", "");
        this.deviceInfo = deviceInfo;
        this.prefixPath = prefixPath;
        Date date = new Date();
        fileName = String.format("%s/%s/%s", deviceInfo, new SimpleDateFormat("yyyy年MM月dd号").format(date), new SimpleDateFormat("HH点mm分ss秒").format(date));

        S_CreateFile();
    }

    int maxMsgNumberLimit = 3000;

    void S_CreateFile() {
        fileIndex = msgIndex / maxMsgNumberLimit;
        _saveFullPath = String.format("%s/logList/%s_%d.html", prefixPath, fileName, fileIndex);

        ssb.delete(0, ssb.length());
        ssb.append(String.format("<html>\r\n<title>%s</title>\r\n<body bgcolor='#222222'>\r\n", deviceInfo));
        String ss = "<script type='text/javascript'>\n" + "window.onload = function(){\n"
                + "     var fonts = document.getElementsByTagName('font');\n"
                + "     for (var i = 0, j = fonts.length; i < j; i++) {\n"
                + "         if (fonts[i].color == '#006060') {\n"
                + "             fonts[i].style.display = 'none';\n"
                + "             var br = fonts[i].nextElementSibling;\n"
                + "             if (br.nodeName != 'br') br.style.display = 'none';\n"
                + "         } else {\n"
                + "             fonts[i].onclick = function(){\n"
                + "                 var next = this.nextElementSibling;\n"
                + "                 if (next.nodeName != 'font') next = next.nextElementSibling;\n"
                + "                 if (next.style.display == 'none')\n"
                + "                     next.style.display = 'block';\n"
                + "                 else\n"
                + "                     next.style.display = 'none';\n"
                + "             }\n"
                + "         }\n"
                + "     }\n"
                + " }\n"
                + "</script> \n";
        ssb.append(ss);
        ssb.append(String.format("<font size = '3' color = '#00bb88' > %s </font><br/>\r\n", fileName));
        ssb.append("<br/>");
        S_Writer(ssb.toString());
    }

    @Override
    public void S_Log(int type, String tag, String time, String log, String stackTrace) {
        m_Log mm = new m_Log();
        mm.msgType = type;
        mm.msgIndex = msgIndex++;
        mm.log = log;
        mm.stackTrace = stackTrace;

        mm.time = time + "";
        if (fileIndex != msgIndex / maxMsgNumberLimit) {
            S_CreateFile();
        }
        logList.add(mm);
        if (logList.size() > 10) {
            SaveData();
        }
    }

    List<m_Log> logList = new ArrayList<>();

    public static void S_SaveData() {
        for (int i = 0; i < o_localLogs.size(); i++) {
            C_LogTxtSave mm = o_localLogs.get(i);
            mm.SaveData();
            System.out.println("log保存成功: " + mm._saveFullPath);
        }
    }

    public static void S_ClearAll() {
        for (int i = 0; i < o_localLogs.size(); i++) {
            o_localLogs.get(0).S_Clear();
            i--;
        }
    }

    public void S_Clear() {
        try {
            SaveData();
            bw.flush();
            o_localLogs.remove(0);
        } catch (Exception ex) {
            System.err.printf("错误.....保存失败");
            ex.fillInStackTrace();
        }
    }

    void SaveData() {
        ssb.delete(0, ssb.length());
        for (int i = 0; i < logList.size(); i++) {
            m_Log logData = logList.get(i);
            String log = logData.log.replace("\n", "<br>&ensp;&ensp;&ensp;&ensp;");

            String[] sss = C_String.S_GetLogColor(log);
            String color = sss[0];
            log = sss[1];
            if (false) {
                switch (logData.msgType) {
                    case 0://Error
                        if (color == null) color = "990022";
                        ssb.append("\t<font size = '1' color = '#").append(color).append("' style='background-color:#220000' > ").append(logData.msgIndex).append(">-  ").append(log).append("</font><br/>\r\n");
                        break;
                    case 1://Assert
                        if (color == null) color = "9999bb";
                        ssb.append("\t<font size = '1' color = '#").append(color).append("' > ").append(logData.msgIndex).append(">-  ").append(log).append("</font><br/>\r\n");
                        break;
                    case 2://Warning
                        if (color == null) color = "999900";
                        ssb.append("\t<font size = '1' color = '#").append(color).append("' style='background-color:#444400' > ").append(logData.msgIndex).append(">-  ").append(log).append("</font><br/>\r\n");
                        break;
                    case 3://Log
                        if (color == null) color = "609940";
                        ssb.append("\t<font size = '1' color = '#").append(color).append("' > ").append(logData.msgIndex).append(">-  ").append(log).append("</font><br/>\r\n");
                        break;
                    case 4://Exception
                        if (color == null) color = "ff00ff";
                        ssb.append("\t<font size = '1' color = '#").append(color).append("' style='background-color:#880088' > ").append(logData.msgIndex).append(">-  ").append(log).append("</font><br/>\r\n");
                        break;
                }
                ssb.append("\t<font size = '1' color = '#006060' > ").append(logData.time).append("===>").append(logData.stackTrace.replace("\n", "<br>")).append("</font><br/>\r\n");
            } else {
                switch (logData.msgType) {
                    case 0://Error
                        if (color == null) color = "990022";
                        ssb.append(String.format("\t<font size = '1' color = '#%s' style='background-color:#220000' > %d>-  %s</font><br/>\r\n", color, logData.msgIndex, log));
                        break;
                    case 1://Assert
                        if (color == null) color = "9999bb";
                        ssb.append(String.format("\t<font size = '1' color = '#%s' > %d>-  %s</font><br/>\r\n", color, logData.msgIndex, log));
                        break;
                    case 2://Warning
                        if (color == null) color = "999900";
                        ssb.append(String.format("\t<font size = '1' color = '#%s' style='background-color:#444400' > %d>-  %s</font><br/>\r\n", color, logData.msgIndex, log));
                        break;
                    case 3://Log
                        if (color == null) color = "609940";
                        ssb.append(String.format("\t<font size = '1' color = '#%s' > %d>-  %s</font><br/>\r\n", color, logData.msgIndex, log));
                        break;
                    case 4://Exception
                        if (color == null) color = "ff00ff";
                        ssb.append(String.format("\t<font size = '1' color = '#%s' style='background-color:#880088' > %d>-  %s</font><br/>\r\n", color, logData.msgIndex, log));
                        break;
                }
                ssb.append(String.format("\t<font size = '1' color = '#006060' > %s===>%s</font><br/>\r\n", logData.time, logData.stackTrace.replace("\n", "<br>")));
            }
        }
        //ssb.AppendFormat("</body>\r\n</html>");
        S_Writer(ssb.toString());
        //C_Log.LogError("S_SaveData---------------------" + logList.Count);
        logList.clear();
    }

    ///
    BufferedWriter S_Writer(String ss) {
        if (bw == null) {
            File fi = new File(_saveFullPath);
            try {
                if (fi.exists() == false) {
                    if (fi.getParentFile().exists() == false) {
                        fi.getParentFile().mkdirs();
                    }
                    fi.createNewFile();
                }
                FileOutputStream fiou = new FileOutputStream(fi, true);
                OutputStreamWriter opw = new OutputStreamWriter(fiou, "UTF-8");
                bw = new BufferedWriter(opw);
            } catch (Exception e) {
                System.out.println("log保存失败.....: " + e.getMessage() + "...\n" + e.getStackTrace());
                return null;
            }
        }
        try {
            bw.newLine();
            bw.write(ss);
            bw.flush();
        } catch (Exception e) {

        }
        return bw;
    }
}


class m_Log {
    public int msgType;
    public long msgIndex;
    public String time, tag, log, stackTrace;
}

